#!/usr/bin/env python
# -*- coding: utf-8 -*-

#
# This program is free software; you can redistribute it and/or modify  
# it under the terms of the GNU General Public License as published by  
# the Free Software Foundation; either version 2 of the License, or     
# (at your option) any later version.                                   
#                                                                         
# A copy of the license can be found in the license.txt file supplied   
# with this software or at: http://www.gnu.org/copyleft/gpl.html       
#


import time
import select
import threading

from help import logging


class   Stablizer(threading.Thread) :

    INTERVAL_STABLIZE = 60
    INTERVAL_FIX_FINGER = 60

    def __init__(self, node) :
        threading.Thread.__init__(self )

        self.node = node

        self.__serving = True
        self.__is_stop = threading.Event()

        self._countdown_stablize = self.INTERVAL_STABLIZE
        self._countdown_fix_finger = self.INTERVAL_FIX_FINGER

        self.logger = logging.getLogger('OpenChord')
        ## __init__()

    def run(self) :
        poll_interval = 0.5
        while self.__serving :
            r,w,e = select.select([],[],[],poll_interval)

            self._countdown_stablize -= 1
            if self._countdown_stablize <= 0 :
                self.stablize()
                self._countdown_stablize = self.INTERVAL_STABLIZE

            self._countdown_fix_finger -= 1
            if self._countdown_fix_finger <= 0 :
                self.fixFingers()
                self._countdown_fix_finger = self.INTERVAL_FIX_FINGER
            # while

        self.__is_stop.set()
        ## run()

    def stop(self) :
        self.__serving = False
        self.__is_stop.wait()
        ## stop()

    #### --------------------------------------------------------- ####

    def stablize(self) :
        try :
            self.node.stablize()
        except :
            self.logger.excpt()
        ## stablize()

    def fixFingers(self) :
        try :
            self.node.fixFingers()
        except :
            self.logger.excpt()
        ## fixFinger()

    ## class Stablizer

